package cn.sjlink.util;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AccessTokenUtil {
    private final Logger logger = Logger.getLogger(getClass());

    private static final String stack_token_url = "http://w3.morninggo.cn/oauth/token?scope=tiamoo_api&client_id=tiamoo&client_secret=a0ea3fa20dbd7bb4d5abf1d59d63bae8&grant_type=client_credentials";

    public String getStackToken()throws Exception{
        JedisUtil redisUtil = JedisUtil.getRedisUtil();
        if(StringUtils.isNotEmpty(redisUtil.getKey("stackToken"))){
            return String.valueOf(redisUtil.getKey("stackToken"));
        }else{
            String s = HttpClientUtil.doPost(stack_token_url, "");
            logger.info(s);
            Map<String, Object> map = JsonUtil.jsonToMap(s);
            String token = String.valueOf(map.get("access_token"));
            Integer expires_in = Integer.parseInt(String.valueOf(map.get("expires_in")));
            if(StringUtils.isNotEmpty(token)){
                redisUtil.setex("stackToken",expires_in,token);
                return token;
            }else{
                return "";
            }
        }
    }

}
